<template>
  <div>
    <el-descriptions class="margin-top" title="模型详情" :column="3"  border>
      <template slot="extra">
      <el-button type="primary" size="small"  @click="submitForm(DataForm)">保存</el-button>
      </template>
      <el-descriptions-item>
        <template slot="label">
          <i class="el-icon-user"></i>
          模型名称
        </template>
        <el-input style="width: 100%;" v-model="DataForm.modelName">
      </el-input>
      </el-descriptions-item>
      <el-descriptions-item>
        <template slot="label">
          <i class="el-icon-position"></i>
          模型文件路径
        </template>
        <el-input
          placeholder="请上传模型代码"
          v-model="DataForm.modelPath"
          :disabled="true">
        </el-input>
      </el-descriptions-item>
      <el-descriptions-item>
        <template slot="label">
          <i class="el-icon-time"></i>
          更改时间
        </template>
        {{ DataForm.updateTime }}
      </el-descriptions-item>
      <el-descriptions-item>
        <template slot="label">
          <i class="el-icon-tickets"></i>
          模型标签
        </template>
        <el-tag size="small">{{DataForm.modelTag }}</el-tag>
      </el-descriptions-item>
      <el-descriptions-item>
        <template slot="label">
          <i class="el-icon-office-building"></i>
          模型简介
        </template>
        <el-input v-model="DataForm.modelDesc">
      </el-input>
      </el-descriptions-item>
    </el-descriptions>

    <el-upload
          ref="upload"
          action=""
          :auto-upload="false"
          :file-list="fileList"
          :limit="1"
          :on-exceed="handleExceed"
          :on-change="handleChange"
          :on-remove="handleRemove"
          :on-preview="handlePreview"
          :http-request="httpRequest">
          <el-button size="small" type="primary" >选择文件</el-button>
        </el-upload>
    <pre v-if="fileContent" style="font-family:Arial;background-color:#F2F6FC;">{{ fileContent }}</pre>
    <el-empty v-else description="请上传模型代码"></el-empty>
    <div style="float: right;"slot="footer" class="dialog-footer">
      <el-button size="small" type="success" class="title"  @click.stop="uploadData">上传保存</el-button>
      <el-button size="small" @click='returnModel'>取消</el-button>
    </div>
  </div>
</template>

<script>
import {
  ModelSave,
  getModelById,
  modelUpload
} from '../../api/userMG'

export default {
  data() {
    return {
      fileList: [],
      fileContent: '',
      DataForm: {
        id:'',
        modelName:'',
        modelDesc:'',
        modelPath:'',
        modelTagId:'',
        modelTag:'',
        updateTime:'',
      },
    };
  },
  created() {
    this.DataForm.id = this.$route.params.id;
    this.DataForm.modelName = this.$route.params.modelName;
    this.DataForm.modelDesc = this.$route.params.modelDesc;
    this.DataForm.modelPath = this.$route.params.modelPath;
    if(this.DataForm.modelPath!=''){
      const defaultFileList=[{name: this.DataForm.modelPath.split("\\").pop(),url:this.DataForm.modelPath}]
      this.fileList=defaultFileList
    }else{
      this.fileList=[]
    }

    this.DataForm.modelTagId = this.$route.params.modelTagId;
    this.DataForm.modelTag = this.$route.params.modelTag;
    this.DataForm.updateTime = this.$route.params.updateTime;
  },

  methods: {
    handleExceed(files, fileList) {
      console.log(fileList)
    this.$message.warning(`当前限制选择 1 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`);
  },
  handleRemove(file) {
      // 移除文件的操作
      console.log('移除文件: ', file.name);
      this.fileList[0].name=null
      this.fileList[0].url=null
      this.fileContent=''
    },
    httpRequest(param) {
      const formData = new FormData();
      formData.append('file', param.file);
      formData.append('modelId', this.DataForm.id);
      formData.append('modelTagId', this.DataForm.modelTagId);
      modelUpload(formData).then(res=>{
        if (res.code==200) {
            this.DataForm.modelPath=res.data
            this.fileList=[{name: param.file.name,url:this.DataForm.modelPath}]
            this.submitForm(this.DataForm)
          }
        else{
            this.$message.error('error')
        }
      }).catch(err => {
          this.loading = false
          this.$message.error('上传文件失败，请稍后再试！')
        })
    },
    handlePreview(file) {
      // 预览文件的操作
      console.log('预览文件: ', file.name);
      fetch('http://127.0.0.1:5000/modelDownload?fileName='+file.name+'&modelId='+this.DataForm.id+'&modelTagId='+this.DataForm.modelTagId)
      .then(response => {
          if(response.ok) {
              // 如果服务器返回了200状态码，那么下载文件
              let link = document.createElement('a');
              link.href = response.url;
              link.download = file.name;
              link.click(); // 触发点击事件来下载文件
              this.$message.success('文件正在下载！');
              console.log(response)
          } else {
              // 如果服务器返回了其他状态码，那么显示错误消息
              this.$message.error('文件不存在或失效，请重新上传！');
          }
      })
      .catch(error => {
          console.log('发生错误: ', error)
          this.$message.error('文件不存在或失效，请重新上传！');
      });
    },
    handleChange(file, fileList) {
      this.fileList = fileList;
      if (file.raw) {
        const reader = new FileReader();
        reader.onload = e => {
          this.fileContent = e.target.result;
        };
        reader.readAsText(file.raw);
      }
    },
    uploadData(){
      this.$refs.upload.submit()
    },
    returnModel: function(index, row){
      this.$router.push({
        name: "模型管理", // 路由的名字
      });
    },
    // 编辑、增加保存方法
    submitForm(DataForm) {
      ModelSave(this.DataForm)
        .then(res => {
          if (res.code==200) {
            this.$message({
              type: 'success',
              message: '模型保存成功！'
            })
            getModelById(this.DataForm.id)
            .then(res => {
              if (res.code!=200) {
                this.$message({
                  type: 'info',
                  message: res.msg
                })
              } else {
                this.DataForm.updateTime=res.data.updateTime
                // 分页赋值
              }
            })
            .catch(err => {
              this.$message.error('获取数据失败，请稍后再试！')
            })
          } else {
            this.$message({
              type: 'info',
              message: res.msg
            })
          }
        })
        .catch(err => {
          this.$message.error('模型保存失败，请稍后再试！')
        })
    },
  }
};
</script>
